package com.cms.controller.front.member;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;

import org.apache.commons.lang.StringUtils;

import com.cms.Feedback;
import com.cms.controller.front.BaseController;
import com.cms.entity.Member;
import com.cms.entity.Payment;
import com.cms.entity.Withdraw;
import com.cms.routes.RouteMapping;

@RouteMapping(url = "/member/withdraw")
public class WithdrawController extends BaseController{
	
	/**
	 * 申请
	 */
	public void index(){
		Member member = new Member().dao().findById(getCurrentMember().getId());
		if(StringUtils.isBlank(member.getMobile())){
			redirect("/member/bind");
			return;
		}
		if(StringUtils.isBlank(member.getAccount())){
			redirect("/member/account");
			return;
		}
		setAttr("member", member);
		render("/templates/"+getTheme()+"/"+getDevice()+"/member_withdraw.html");
	}
	
	/**
	 * 列表
	 */
	public void list(){
		Integer pageNumber = getParaToInt("pageNumber");
		if(pageNumber==null){
			pageNumber=1;
		}
		int pageSize = 10 ; 
		Member currentMember = getCurrentMember();
		setAttr("page",new Withdraw().dao().findPage(pageNumber,pageSize,currentMember.getId(),null));
		setAttr("member", new Member().dao().findById(getCurrentMember().getId()));
		render("/templates/"+getTheme()+"/"+getDevice()+"/member_withdraw_list.html");
	}
	
	/**
	 * 申请
	 */
	public void apply(){
		Member member = new Member().dao().findById(getCurrentMember().getId());
		if(StringUtils.isBlank(member.getAccount())){
			redirect("/member/account");
			return;
		}
		setAttr("member", member);
		render("/templates/"+getTheme()+"/"+getDevice()+"/member_withdraw_apply.html");
	}
	
	/**
	 * 保存申请提现
	 */
	public void saveApply(){
		Member member = new Member().dao().findById(getCurrentMember().getId());
		Withdraw withdraw = getModel(Withdraw.class,"",true);
		if(member.getAmount().compareTo(withdraw.getAmount())==-1){
			renderJson(Feedback.error("提现金额不能大于当前余额"));
			return;
		}
		
		withdraw.setAccount(getCurrentMember().getAccount());
		withdraw.setAccountType(getCurrentMember().getAccountType());
		withdraw.setStatus(0);
		withdraw.setMemberId(getCurrentMember().getId());
		withdraw.setCreateDate(new Date());
		withdraw.setModifyDate(new Date());
		withdraw.save();
		
		Payment payment = new Payment();
		payment.setType(Payment.Type.WITHDRAW.ordinal());
		payment.setCreateDate(new Date());
		payment.setModifyDate(new Date());
		payment.setMemberId(withdraw.getMemberId());
		payment.setOrderId(null);
		payment.setAmount(withdraw.getAmount());
		payment.setInout("-");
		payment.save();
		
		BigDecimal newAmount = member.getAmount().subtract(withdraw.getAmount());
		member.setAmount(newAmount);
		member.update();
		
		renderJson(Feedback.success(new HashMap<>()));
	}
	
}
